﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.Utils;
using DevExpress.XtraEditors;
using FileManager_Client.BusinessLogic;
using FileManager_Client.BusinessLogic.FileManagerUserService;
using FileManager_Client.Utility;

namespace FileManager_Client.PresentationLayer.NewUi
{
    public partial class AddFileForm : BaseForm
    {
        #region Form Constructor
        private UserLoginResult userSession;
        private List<string> _hasFolderNameCollection;
        private string _parentFolderId;
        private FileService fileService;
        private FileManager_Form _fileManagerForm;
        private static object lockWait = new object();
        private LoadingWaitForm loadingWaitForm;
        public AddFileForm(List<string> hasFolderNameCollection, string parentFolderId, FileManager_Form fileManagerForm)
        {
            InitializeComponent();
            _hasFolderNameCollection = hasFolderNameCollection;
            userSession = CacheGlobal.GetCache(GlobalString.System_Config_String.UserSession) as UserLoginResult;
            fileService = new FileService();
            _parentFolderId = parentFolderId;
            _fileManagerForm = fileManagerForm;
            Ttc_Message.ShowShadow = true;
            Ttc_Message.Rounded = true;
            Ttc_Message.ShowBeak = true;
            Ttc_Message.SetToolTipIconType(Tb_NewFolderName, ToolTipIconType.Information);
        }
        #endregion

        #region Button Confirm Event
        private void Btn_Confrim_Click(object sender, EventArgs e)
        {
            if (CheckFolderName())
                CreateNewFolder();
        } 
        #endregion

        #region Button Cancel Event
        private void Btn_Cancel_Click(object sender, EventArgs e)
        {
            Close();
        }
        #endregion

        #region Txtbox Event
        private void Tb_NewFolderName_TextChanged(object sender, EventArgs e)
        {
            Ttc_Message.HideHint();
        }

        private void Tb_NewFolderName_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar != 13) return;
            if (CheckFolderName())
                CreateNewFolder();
        }
        #endregion

        #region Check Foder Name Method
        private bool CheckFolderName()
        {
            Ttc_Message.HideHint();
            var folderName = Tb_NewFolderName.Text;
            if (folderName.IndexOfAny(System.IO.Path.GetInvalidFileNameChars()) != -1)
            {
                Ttc_Message.ShowHint("文件夹名称不能包含\\/:*?\"<>| 特殊字符!", Tb_NewFolderName, ToolTipLocation.BottomCenter);
                return false;
            }
            if (string.IsNullOrEmpty(folderName.Trim()))
            {
                Ttc_Message.ShowHint("文件名不能为空!", Tb_NewFolderName, ToolTipLocation.BottomCenter);
                return false;
            }
            if (_hasFolderNameCollection.Contains(folderName))
            {
                Ttc_Message.ShowHint("该文件夹中已经包含了这个名称!", Tb_NewFolderName, ToolTipLocation.BottomCenter);
                return false;
            }
            return true;
        }
        #endregion

        #region Create Folder Method
        private void CreateNewFolder()
        {
            try
            {
                lock (lockWait)
                {
                    loadingWaitForm = new LoadingWaitForm();
                    loadingWaitForm.SetCaption(GlobalString.System_Config_String.MbxInfoStr);
                    loadingWaitForm.SetDescription(GlobalString.System_Config_String.FileReNameStr);
                }
                var backgroundWorker = new BackgroundWorker();
                backgroundWorker.DoWork += backgroundWorker_DoWork;
                var newFolderArgs = new NewFolderArgs
                {
                    NewFolderNamek__BackingField = Tb_NewFolderName.Text,
                    ParentFolderSidk__BackingField = _parentFolderId,
                    UserIdk__BackingField = userSession.UserIdk__BackingField
                };
                backgroundWorker.RunWorkerAsync(newFolderArgs);
                loadingWaitForm.ShowDialog();
            }
            catch (Exception ex)
            {
                LogLoader.Instance.Log.Error("CreateNewFolder has problem", ex);
                XtraMessageBox.Show("创建文件夹失败!", GlobalString.System_Exception_String.MbxErrorStr, MessageBoxButtons.OK,
                                    MessageBoxIcon.Error);
            }
        }

        void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                var newFolderArgs = e.Argument as NewFolderArgs;
                var reslut = fileService.CreateFolder(newFolderArgs);

                if (reslut.Resultk__BackingField)
                {
                    Invoke((EventHandler)delegate
                    {
                        loadingWaitForm.SetCaption("创建文件夹成功!");
                    });
                    var _userService = new UserService();
                    Invoke((EventHandler)delegate
                    {
                        loadingWaitForm.SetCaption(GlobalString.System_Config_String.CreateFolderLoadingFolderStr);
                    });
                    var folderCollectionResult = _userService.SyncGetFolderService();
                    CacheGlobal.Add(GlobalString.System_Config_String.FolderCollectionCache, folderCollectionResult.Result);
                    Invoke((EventHandler)delegate
                    {
                        loadingWaitForm.SetCaption(GlobalString.System_Config_String.CreateFolderLoadingFolderRoleStr);
                    });
                    var folderRoleCollectionResult = _userService.SyncGetFolderRoleService();
                    CacheGlobal.Add(GlobalString.System_Config_String.FolderRoleCollectionCache, folderRoleCollectionResult.Result);
                    Invoke((EventHandler)delegate
                    {
                        loadingWaitForm.Close();
                    });
                    Invoke((EventHandler)delegate
                    {
                        Close();
                    });
                }
                else
                {
                    var message = string.Empty;
                    switch (reslut.ResultExceptionk__BackingField)
                    {
                        case BaseExceptionEnum.CreateFolderException:
                            message = GlobalString.System_Exception_String.CreateFolderException;
                            break;
                        case BaseExceptionEnum.CreateFolderHaveFolderExpcetion:
                            message = GlobalString.System_Exception_String.CreateFolderHaveFolderExpcetion;
                            break;
                    }
                    XtraMessageBox.Show(message, GlobalString.System_Exception_String.MbxErrorStr, MessageBoxButtons.OK,
                                        MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                LogLoader.Instance.Log.Error("CreateNewFolder backgroundWorker_DoWork has problem", ex);
                XtraMessageBox.Show("创建文件夹失败!", GlobalString.System_Exception_String.MbxErrorStr, MessageBoxButtons.OK,
                                        MessageBoxIcon.Error);
                Invoke((EventHandler)delegate
                {
                    Close();
                });
            }
        }
        #endregion
    }
}